#include "mesh3dcache.h"

Mesh3DCache *Mesh3DCache::self = 0L;

Mesh3DCache::Mesh3DCache(QObject *parent) :
    QObject(parent)
{
}

Mesh3DCache::~Mesh3DCache()
{
    // clear the cache
    QMap <QString, Mesh*>::iterator it;
    for (it=MeshCache.begin(); it!=MeshCache.end(); it++)
        delete (*it);
    MeshCache.clear();
}

Mesh3DCache *Mesh3DCache::instance()
{
    if (!self)
        self = new Mesh3DCache();
    return self;
}
//----------------------------------------------------------

Mesh* Mesh3DCache::loadMesh(QString filename)
{
    Mesh *mesh = MeshCache.value(filename, 0L);
    if (mesh)
        return mesh;

    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug(QString("file '" + filename + "' open failed.").toAscii().constData());
        return 0L;
    }

    QTextStream stream(&file);
    mesh = new Mesh(&stream);

    file.close();

    qDebug(QString("model '" + filename + "' loaded").toAscii().constData());

//    mesh->setMinMaxValues();
    MeshCache[filename] = mesh;
    return mesh;
}
